package icu.yougan.trade.controller;

import icu.yougan.trade.entity.ChatMessage;
import icu.yougan.trade.entity.User;
import icu.yougan.trade.enums.ErrorMsg;
import icu.yougan.trade.service.ChatService;
import icu.yougan.trade.service.UserService;
import icu.yougan.trade.vo.R;
import jakarta.annotation.Resource;
import lombok.Data;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chat")
public class ChatController {

    private final SimpMessagingTemplate messagingTemplate;
    private final ChatService chatService;
    private final UserService userService;

    public ChatController(SimpMessagingTemplate messagingTemplate,
                          ChatService chatService,
                          UserService userService) {
        this.messagingTemplate = messagingTemplate;
        this.chatService = chatService;
        this.userService = userService;
    }
    /**
     * 通过authentication获取用户id
     * @param authentication
     * @return
     */
    private Long getUserId(Authentication authentication) {
        User userByAccountNum = userService.getUserByAccountNum(authentication.getName());
        return userByAccountNum.getId();
    }
    // 消息推送路径包含用户ID
    @MessageMapping("/private")
    public void handlePrivateMessage(@Payload ChatMessage message, Authentication auth) {
        Long senderId = getUserId(auth);
        message.setSender(senderId);
        // 调试日志
        System.out.printf("消息路由：发送者 %d → 接收者 %d | 内容: %s%n",
                senderId, message.getReceiver(), message.getContent());
        // 保存消息到数据库
        chatService.saveMessage(message);
        // 精确推送到目标用户
        messagingTemplate.convertAndSendToUser(
                message.getReceiver().toString(),
                "/queue/private",
                message
        );
        // 发送者副本
        messagingTemplate.convertAndSendToUser(
                senderId.toString(),
                "/queue/sent",
                message
        );
    }

    @MessageMapping("/item/{itemId}")
    public void handleItemMessage(@DestinationVariable Long itemId,
                                  @Payload ChatMessage message,
                                  Authentication authentication) {
        Long sender = getUserId(authentication);
        message.setSender(sender);
        message.setItemId(itemId);
        // 设置默认值
        if (message.getIsRead() == null) {
            message.setIsRead(false);
        }
        if (message.getStatus() == null) {
            message.setStatus(true);
        }
        chatService.saveMessage(message);
        // 广播到商品聊天室
        messagingTemplate.convertAndSend(
                "/topic/item/" + itemId,
                message);
        // 同时发送给私聊双方（确保接收者能收到）
        if (message.getReceiver() != null) {
            messagingTemplate.convertAndSendToUser(
                    message.getReceiver().toString(),
                    "/queue/private",
                    message
            );
        }
    }

    @GetMapping("/conversations")
    public R getConversations(Authentication authentication) {
        Long userId = getUserId(authentication);
        return R.success(chatService.getConversations(userId));
    }

    @GetMapping("/private-messages")
    public R getPrivateMessages(@RequestParam Long targetUser,
                                Authentication authentication) {
        System.out.println("正在获取当前私聊信息！");
        Long userId = getUserId(authentication);
        return R.success(chatService.getPrivateMessages(userId, targetUser));
    }

    @GetMapping("/item-messages")
    public R getItemMessages(@RequestParam Long itemId) {
        return R.success(chatService.getItemMessages(itemId));
    }

    @PostMapping("/mark-read")
    public R markAsRead(@RequestBody Map<String, Object> request,Authentication authentication) {
            String messageId = request.get("messageId").toString();
        //System.out.println("获取的request参数为:"+request);
        Long userId = getUserId(authentication);
        chatService.markMessagesAsRead(messageId,userId);
            return R.success();
    }

    @GetMapping("/private-conversations")
    public R getPrivateConversations(Authentication authentication) {
        Long userId = getUserId(authentication);
        return R.success(chatService.getPrivateConversations(userId));
    }
    @GetMapping("/private-history")
    public R getPrivateHistory(@RequestParam Long targetUser,
                               Authentication authentication) {
        Long userId = getUserId(authentication);
        return R.success(chatService.getPrivateMessages(userId, targetUser));
    }
    @Data
    static class DeleteRequest {
        private List<Long> messageIds;
        private Long senderId;
        private Long receiverId;
    }
    @PostMapping("/delete")
    public R deleteConversations(@RequestBody DeleteRequest request,Authentication authentication) {
        System.out.println("chatController中的数据为："+request);
        List<Long> ids = request.getMessageIds();
        Long senderId = request.getSenderId();
        Long receiverId = request.getReceiverId();
        Long deleteUserId=getUserId(authentication);
        if (ids == null || ids.isEmpty()) {
            return R.fail(ErrorMsg.PARAM_ERROR);
        }
        return R.success(chatService.deleteConversations(ids, senderId, receiverId,deleteUserId));
    }
}